<template>
  <div>
    <div v-if="messageStatus">
      <n-card title="商品列表" header>
        <div class="header">
          <div>
            <NButton type="primary" @click="onClickAdd"> 添加商品 </NButton>
          </div>
          <div>
            <n-input-group>
              <n-input
                multiple
                v-model:value="params.keyword"
                clearable
                placeholder="请输入插件关键词"
                :style="{ width: '100%' }"
              />
              <n-button @click="List" type="primary" ghost> 搜索 </n-button>
            </n-input-group>
          </div>
        </div>
      </n-card>
      <div class="box" :style="'height:' + innerHeights">
        <!-- 数据表 -->
        <div class="table-box">
          <n-data-table
            striped
            :scroll-x="1800"
            :loading="messageParams.loading"
            ref="table"
            :columns="columns"
            :data="data"
          />
        </div>
      </div>
      <div class="pagination">
        <div>共{{ pagination.total }}条数据</div>
        <div>
          <n-pagination
            :page="params.pageNum"
            :page-size="params.pageSize"
            :item-count="pagination.total"
            size="medium"
            show-size-picker
            :page-slot="8"
            :page-sizes="pageSizes"
            :on-update:page="pageNext"
            :on-update:page-size="sizeNext"
          />
        </div>
      </div>
    </div>

    <div v-else class="Message">
      <n-result
        status="403"
        title="403 禁止访问"
        description="总有些门是对你关闭的"
      >
        <template #footer>
          <n-button @click="goTo('/pluginAdmin/all')">去充钱</n-button>
        </template>
      </n-result>
    </div>

    <n-drawer
      v-model:show="showModal"
      :default-width="900"
      :default-height="innerHeights1"
      :placement="'right'"
      resizable
    >
      <n-drawer-content :title="popTitle">
        <div class="box-modal">
          <n-form
            ref="formRef"
            :model="formValue"
            :rules="rules"
            class="formClass"
            :style="'height:' + (innerHeights1 - 100) + 'px'"
          >
            <n-form-item label="连锁店铺">
              <n-select
                v-model:value="formValue.businessId"
                :style="{ width: '400px' }"
                filterable
                :multiple="popTitle == '编辑' ? false : true"
                placeholder="请选择店铺"
                :options="storeOptions"
                clearable
              />
            </n-form-item>
            <n-form-item label="商品分类">
              <!-- <n-select
              v-model:value="formValue.categoryId"
                :style="{ width: '400px' }" 
                filterable 
                placeholder="请选择商品分类"
                :options="categoryOptions"
                clearable
              /> -->

              <n-cascader
                v-model:value="value"
                placeholder="请选择商品分类"
                :expand-trigger="hoverTrigger ? 'hover' : 'click'"
                :options="options"
                :check-strategy="checkStrategyIsChild ? 'child' : 'all'"
                :show-path="showPath"
                clearable
                :filterable="filterable"
                @update:value="handleUpdateValue"
              />
            </n-form-item>
            <n-form-item label="商品名称" path="goodsName">
              <n-input
                :style="{ width: '400px' }"
                v-model:value="formValue.goodsName"
                placeholder="请输入商品名称"
              />
            </n-form-item>
            <n-form-item label="副标题">
              <n-input
                :style="{ width: '400px' }"
                v-model:value="formValue.subtitle"
                placeholder="请输入副标题"
              />
            </n-form-item>
            <n-form-item label="商品价格" path="goodsName">
              <n-input
                :style="{ width: '400px' }"
                v-model:value.number="formValue.goodsPrice"
                placeholder="请输入商品价格"
              />
            </n-form-item>
            <n-form-item label="划线价格" path="goodsName">
              <n-input
                :style="{ width: '400px' }"
                v-model:value.number="formValue.scribePrice"
                placeholder="请输入划线价格"
              />
            </n-form-item>
            <n-form-item label="会员价格" path="goodsName">
              <n-input
                :style="{ width: '400px' }"
                v-model:value.number="formValue.memberPrice"
                placeholder="请输入会员价格"
              />
            </n-form-item>
            <n-form-item label="配送方式" path="goodsName">
              <n-select
                v-model:value="formValue.goodsType"
                :style="{ width: '400px' }"
                filterable
                placeholder="请选择配送方式"
                :options="peisonOptions"
                clearable
              />
            </n-form-item>
            <n-form-item label="支付方式" path="goodsName">
              <n-select
                v-model:value="formValue.paypal_type"
                :style="{ width: '400px' }"
                filterable
                placeholder="请选择支付方式"
                :options="paymentOptions"
                clearable
              />
            </n-form-item>
            <!-- <n-form-item label="商品类型" path="goodsName">
            <n-select v-model:value="formValue.order_type"
              :style="{ width: '400px' }" 
              filterable 
              placeholder="请选择商品类型"
              :options="goodsTypeOptions"
              clearable
            />
          </n-form-item> -->
            <n-form-item label="库存" path="goodsName">
              <n-input
                :style="{ width: '400px' }"
                v-model:value="formValue.stockNum"
                placeholder="请输入库存"
              />
            </n-form-item>
            <n-form-item label="赠送积分" path="rewardIntegral">
              <n-input
                :style="{ width: '400px' }"
                v-model:value="formValue.rewardIntegral"
                placeholder="请输入赠送积分"
              />
            </n-form-item>

            <n-form-item label="预览图" path="previewUrl">
              <div
                @click="changeImage('预览图')"
                v-if="formValue.previewUrl"
                style="
                  height: 135px;
                  width: 100px;
                  overflow: hidden;
                  display: flex;
                  padding: 12px;
                  justify-content: center;
                  align-items: center;
                "
              >
                <n-image
                  :preview-disabled="true"
                  style="
                    object-fit: contain;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                  "
                  :src="Https() + formValue.previewUrl"
                />
              </div>
              <div v-else @click="changeImage('预览图')" class="imageUpload">
                <n-icon size="24" color="rgb(49, 108, 114)">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    xmlns:xlink="http://www.w3.org/1999/xlink"
                    viewBox="0 0 16 16"
                  >
                    <g fill="none">
                      <path
                        d="M8 2.5a.5.5 0 0 0-1 0V7H2.5a.5.5 0 0 0 0 1H7v4.5a.5.5 0 0 0 1 0V8h4.5a.5.5 0 0 0 0-1H8V2.5z"
                        fill="currentColor"
                      ></path>
                    </g>
                  </svg>
                </n-icon>
              </div>
            </n-form-item>
            <n-form-item label="轮播图">
              <n-carousel
                style="width: 220px; height: 120px"
                draggable
                :interval="1000"
                centered-slides
                loop
                v-if="formValue.rotationImgsJson.length"
                autoplay
              >
                <n-carousel-item
                  v-for="(item, index) in formValue.rotationImgsJson"
                  style="width: 100%"
                >
                  <n-image
                    :preview-disabled="true"
                    style="
                      object-fit: contain;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                    "
                    :src="Https() + item"
                  />
                </n-carousel-item>
              </n-carousel>
              <div
                @click="changeImage('轮播图')"
                v-if="formValue.rotationImgsJson.length"
                style="
                  height: 135px;
                  width: 100px;
                  overflow: hidden;
                  display: flex;
                  padding: 12px;
                  justify-content: center;
                  align-items: center;
                "
              >
                <n-button @click="List" type="primary" ghost>
                  重新上传
                </n-button>
              </div>
              <div v-else @click="changeImage('轮播图')" class="imageUpload">
                <n-icon size="24" color="rgb(49, 108, 114)">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    xmlns:xlink="http://www.w3.org/1999/xlink"
                    viewBox="0 0 16 16"
                  >
                    <g fill="none">
                      <path
                        d="M8 2.5a.5.5 0 0 0-1 0V7H2.5a.5.5 0 0 0 0 1H7v4.5a.5.5 0 0 0 1 0V8h4.5a.5.5 0 0 0 0-1H8V2.5z"
                        fill="currentColor"
                      ></path>
                    </g>
                  </svg>
                </n-icon>
              </div>
            </n-form-item>

            <n-form-item label="富文本" path="contents">
              <n-button @click="EditorFun">编写富文本</n-button>
            </n-form-item>

            <n-form-item label="商品规格" path="status">
              <n-button @click="SkuFun">设置规格</n-button>
            </n-form-item>

            <n-form-item label="商品推荐" path="extJson">
              <n-switch v-model:value="formValue.extJson">
                <template #checked> 推荐 </template>
                <template #unchecked> 不推荐 </template>
              </n-switch>
            </n-form-item>

            <n-form-item label="商品状态" path="goodsStatus">
              <n-switch v-model:value="formValue.goodsStatus">
                <template #checked> 上架 </template>
                <template #unchecked> 下架 </template>
              </n-switch>
            </n-form-item>
            <n-form-item label="" path="goodsStatus"> </n-form-item>

            <div style="height: 80px"></div>
          </n-form>

          <div
            class="goodsFloot"
            :style="'top:' + (innerHeights1 - 177) + 'px'"
          >
            <div class="Editorfloot">
              <n-button @click="showModal = false">取消</n-button>
              <n-button @click="submitCallback" type="primary"> 提交 </n-button>
            </div>
          </div>
        </div>
      </n-drawer-content>
    </n-drawer>

    <!-- <n-drawer
      v-model:show="EditorShow"
      :default-width="1280"
      :default-height="780"
      :placement="'center'"
      resizable
    >
    </n-drawer> -->
    <yingModal
      :width="'1200px'"
      :height="'600px'"
      :title="'富文本'"
      @close="EditorShow = false"
      @confirm="fuwenben"
      :SkuShow="EditorShow"
    >
      <template #content>
        <!-- <div class="Editorbox"> -->
        <!-- <div :class="'pcEditorClass'"> -->
        <commonEditor
          style="height: 550px"
          :Image="TextImage"
          :token="token"
          @uploadImage="uploadImage"
          :value="formValue.contents"
          @change="getEditorValue"
        />
        <!-- </div>
              <div v-if="EditorClass != 'pcEditorClass'" style=" border: 1px solid #ccc;border-radius: 16px;
                padding: 16px;" :class="EditorClass" v-html="formValue.contents">
              </div> -->
        <!-- </div> -->

        <!-- <div class="Editorfloot">
              <n-button @click="EditorShow=false">取消</n-button>
              <n-button type="info" @click="changeEditorClass">
                {{EditorClass=='pcEditorClass'?'切换小程序格式':'切换成pc格式'}}
              </n-button>
              <n-button @click="fuwenben" type="primary">
                确定
              </n-button>
            </div> -->
      </template>
    </yingModal>

    <yingModal
      :width="'1200px'"
      :height="'600px'"
      :title="'商品规格'"
      @close="closeDodal"
      @confirm="confirmModal"
      :SkuShow="SkuShow"
    >
      <template #content>
        <div>
          <div style="display: flex; gap: 20px">
            <n-button @click="addGoodsTherSku" type="primary">
              添加其它规格
            </n-button>
            <n-button @click="settingPrice('1')"> 重新设置 </n-button>
            <n-button v-if="popTitle == '编辑'" @click="settingPrice('2')">
              数据回显
            </n-button>
          </div>

          <div
            v-if="!settingShow"
            class="skubitian"
            v-for="(item, index) in goodsTherJson"
          >
            <div class="skuTitle">
              <n-input-group>
                <n-input style="width: 222px" v-model:value="item.name" />
                <n-input-group-label>规格标题</n-input-group-label>
              </n-input-group>
            </div>
            <div
              class="skuInput"
              :style="{ marginTop: index1 == 0 ? '' : '30px' }"
              v-for="(item1, index1) in item.list"
            >
              <div
                class="skuDelete"
                style="right: 40px"
                @click="addGoodsTherSkuItem(item, index, item1, index1)"
              >
                添加规格
              </div>
              <div
                class="skuDelete"
                @click="skuDelete1(item, index, item1, index1)"
              >
                删除
              </div>
              <!-- 编码 -->
              <!-- <n-input-group>
                <n-input v-model:value="item1.skuId" />
                <n-input-group-label>编码</n-input-group-label>
              </n-input-group> -->

              <!-- 规格名 -->
              <n-input-group>
                <n-input v-model:value="item1.skuName" />
                <n-input-group-label>规格名</n-input-group-label>
              </n-input-group>

              <!-- 排序 -->
              <n-input-group>
                <n-input
                  @input="skuSrotFun1(item, index)"
                  v-model:value="item1.skuSort"
                />
                <n-input-group-label>排序</n-input-group-label>
              </n-input-group>
            </div>
          </div>

          <div v-else>
            <div class="skubitian">
              <div class="skuTitle">设置规格参数</div>
              <div
                class="skuInput"
                :style="{ marginTop: index == 0 ? '' : '30px' }"
                v-for="(item, index) in goodsSkuJson"
              >
                <!-- <div class="skuDelete" style="right:40px" @click="addGoodsSku">
                  添加规格
                </div>
                <div class="skuDelete" @click="skuDelete(item,index)">
                  删除
                </div> -->
                <!-- id: '',
          value: `${goodsTherJson.value[0].list[index].skuName}}`,
          image:'',
          price:'',
          stock:'', -->
                <n-input-group>
                  <n-input disabled v-model:value="item.value" />
                  <n-input-group-label>规格值</n-input-group-label>
                </n-input-group>
                <n-input-group>
                  <n-input v-model:value="item.id" />
                  <n-input-group-label>编码</n-input-group-label>
                </n-input-group>
                <n-input-group>
                  <n-input v-model:value="item.price" />
                  <n-input-group-label>价格</n-input-group-label>
                </n-input-group>

                <n-input-group>
                  <n-input v-model:value="item.stock" />
                  <n-input-group-label>库存</n-input-group-label>
                </n-input-group>

                <div
                  style="
                    height: 32px;
                    display: flex;
                    align-items: center;
                    gap: 20px;
                  "
                >
                  <span>规格图:</span>
                  <div
                    @click="changeImage('规格图', index)"
                    v-if="item.image"
                    style="height: 32px; width: 32px"
                  >
                    <n-image
                      :preview-disabled="true"
                      style="
                        object-fit: contain;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                      "
                      :src="item.image"
                    />
                  </div>
                  <div
                    v-else
                    @click="changeImage('规格图', index)"
                    class="imageUpload"
                    style="height: 32px; width: 32px"
                  >
                    <n-icon size="24" color="rgb(49, 108, 114)">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        xmlns:xlink="http://www.w3.org/1999/xlink"
                        viewBox="0 0 16 16"
                      >
                        <g fill="none">
                          <path
                            d="M8 2.5a.5.5 0 0 0-1 0V7H2.5a.5.5 0 0 0 0 1H7v4.5a.5.5 0 0 0 1 0V8h4.5a.5.5 0 0 0 0-1H8V2.5z"
                            fill="currentColor"
                          ></path>
                        </g>
                      </svg>
                    </n-icon>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </yingModal>

    <n-modal
      v-model:show="uploadShow"
      :mask-closable="false"
      preset="dialog"
      style="width: 1000px"
      :title="'文件管理'"
      content="你确认?"
      positive-text="确定"
      negative-text="关闭"
      @positive-click="uploadShow = false"
      @negative-click="uploadShow = false"
    >
      <div class="box-upload">
        <Upload type="1" @selectImage="selectImageFun" />
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import yingModal from "@/components/common/YingModal.vue";
import {
  NAvatar,
  NButton,
  NImage,
  NSwitch,
  NTag,
  CascaderOption,
} from "naive-ui";
import type { FormInst } from "naive-ui";
import { nextTick, onMounted, ref, createApp, defineComponent } from "vue";
import Editor from "@/components/Editor/index.vue";
import commonEditor from "@/components/common/commonEditor.vue";
import Upload from "@/views/upload/index.vue";
import api from "./api";
import { forEach } from "lodash-es";
import { sortList } from "@/utils/common.js";

import { Https, setPagination } from "@/utils";
import { globalStore } from "@/store";
const globalStoreData = globalStore();
const router = useRouter();
const route = useRoute();
const pluginInfo = ref({});
const messageStatus = ref(false);
const EditorShow = ref(false);
const value = ref(null);
const hoverTrigger = ref(false);
const options = globalStoreData.typeOptions;
const showPath = ref(true);
const checkStrategyIsChild = ref(true);
const filterable = ref(true);
const EditorClass = ref("pcEditorClass");

const handleUpdateValue = (value: string, option: CascaderOption) => {
  console.log(value, option);
  formValue.value.categoryId = value;
};
const emailForm = ref({
  test_msg: "",
});
const TextImage = ref("");
const getMsg = (val) => {
  formValue.value.contents = val;
};
const changeEditorClass = () => {
  if (EditorClass.value == "pcEditorClass")
    EditorClass.value = "xcxEditorClass";
  else EditorClass.value = "pcEditorClass";
};
const uploadShow = ref(false);
const token = ref("");

const skuInput = ref("");

const goodsTherJson = ref([]);

const goodsSkuJson = ref([
  {
    skuId: "",
    skuName: "",
    skuPrice: "",
    skuStockNum: "",
    skuSort: 0,
    skuImage: "",
  },
]);

const skuSrotFun = (item) => {
  if (goodsSkuJson.value.length > 0) {
    // sortList 排序函数    1.排序方式,2.列表，3.排序字段
    goodsSkuJson.value = sortList("asc", goodsSkuJson.value, "skuSort");
  }
};
const skuSrotFun1 = (item, index) => {
  // sortList 排序函数    1.排序方式,2.列表，3.排序字段
  goodsTherJson.value[index].list = sortList(
    "asc",
    goodsTherJson.value[index].list,
    "skuSort",
  );
};
const settingShow = ref(false);
const settingPrice = (type) => {
  // goodsSkuJson.value = []
  if (type == "2") {
    settingShow.value = !settingShow.value;
    return;
  }

  const newData = [];
  if (!settingShow.value) {
    if (goodsTherJson.value.length == 1) {
      for (let index = 0; index < goodsTherJson.value[0].list.length; index++) {
        newData.push({
          id: `uuid${Math.round(Math.random() * 100000000000000)}`,
          value: `${goodsTherJson.value[0].list[index].skuName}`,
          image: "",
          price: "",
          stock: "",
        });
      }
    }
    if (goodsTherJson.value.length == 2) {
      for (let index = 0; index < goodsTherJson.value[0].list.length; index++) {
        for (
          let index1 = 0;
          index1 < goodsTherJson.value[1].list.length;
          index1++
        ) {
          newData.push({
            id: `uuid${Math.round(Math.random() * 100000000000000)}`,
            value: `${goodsTherJson.value[0].list[index].skuName},${goodsTherJson.value[1].list[index1].skuName}`,
            image: "",
            price: "",
            stock: "",
          });
        }
      }
    }

    if (goodsTherJson.value.length == 3) {
      for (let index = 0; index < goodsTherJson.value[0].list.length; index++) {
        for (
          let index1 = 0;
          index1 < goodsTherJson.value[1].list.length;
          index1++
        ) {
          for (
            let index2 = 0;
            index2 < goodsTherJson.value[2].list.length;
            index2++
          ) {
            console.log(Math.random());
            newData.push({
              id: `uuid${Math.round(Math.random() * 100000000000000)}`,
              value: `${goodsTherJson.value[0].list[index].skuName},${goodsTherJson.value[1].list[index1].skuName},${goodsTherJson.value[2].list[index2].skuName}`,
              image: "",
              price: "",
              stock: "",
            });
          }
        }
      }
    }
  }

  setTimeout(() => {
    goodsSkuJson.value = newData;
    settingShow.value = !settingShow.value;
    console.log(newData, goodsSkuJson.value);
  }, 1000);
};

const closeDodal = (item) => {
  SkuShow.value = false;
};

const fuwenben = () => {
  EditorShow.value = false;
};
const innerHeights = ref(0);
const innerHeights1 = ref(0);
onMounted(() => {
  innerHeights.value = String(window.innerHeight - 280) + "px";
  innerHeights1.value = window.innerHeight;
  token.value = JSON.parse(localStorage.getItem("vue-naivue-admin_auth"))[
    "token"
  ];
  // myPluin()
  storeList();
  //  categoryList();
  List();
});

const skuDelete = (item, currentIndex) => {
  // 通过索引删除数组元素
  // goodsSkuJson.value.splice(index, 1);

  // 通过过滤器删除数组元素
  goodsSkuJson.value = goodsSkuJson.value.filter(
    (item, index) => index !== currentIndex,
  );
};
const skuDelete1 = (item, index, item1, index1) => {
  // 通过索引删除数组元素
  // goodsSkuJson.value.splice(index, 1);

  // 通过过滤器删除数组元素
  goodsTherJson.value[index].list = goodsTherJson.value[index].list.filter(
    (item2, index2) => index2 !== index1,
  );
  if (goodsTherJson.value[index].list.length == 0) {
    goodsTherJson.value = goodsTherJson.value.filter(
      (item2, index2) => index2 !== index,
    );
  }
};

const getEditorValue = (data) => {
  formValue.value.contents = data;
};

const selectImageFun = (selectImageList) => {
  console.log(typeImage.value, skuIndex.value);
  if (typeImage.value == "富文本") {
    TextImage.value = Https() + selectImageList[0];
    uploadShow.value = false;
    return;
  }
  if (typeImage.value == "规格图") {
    goodsSkuJson.value[skuIndex.value].image = Https() + selectImageList[0];
    uploadShow.value = false;
    return;
  }

  if (typeImage.value == "预览图")
    formValue.value.previewUrl = selectImageList[0]; // 只获取第一张图
  else formValue.value.rotationImgsJson = selectImageList; // 只获取第一张图
  uploadShow.value = false;
};

const pageSizes = [
  {
    label: "10 每页",
    value: 10,
  },
  {
    label: "20 每页",
    value: 20,
  },
  {
    label: "30 每页",
    value: 30,
  },
  {
    label: "40 每页",
    value: 40,
  },
];

// 订单类型，1普通订单，2月卡订单，3补录订单，4积分订单，5余额订单
const goodsTypeOptions = ref([
  {
    label: "普通订单",
    value: 1,
  },
  {
    label: "月卡订单",
    value: 2,
  },
  {
    label: "补录订单",
    value: 3,
  },
  {
    label: "积分订单",
    value: 4,
  },
  {
    label: "余额订单",
    value: 5,
  },
]);
// 支付类型，1微信支付、2支付宝支付、3余额支付、4月卡支付
const paymentOptions = ref([
  {
    label: "微信支付",
    value: 1,
  },
  {
    label: "支付宝支付",
    value: 2,
  },
  {
    label: "余额支付",
    value: 3,
  },
  {
    label: "月卡支付",
    value: 4,
  },
  {
    label: "微信,支付宝,余额",
    value: 5,
  },
  {
    label: "全部",
    value: 6,
  },
]);
const peisonOptions = ref([
  {
    label: "快递",
    value: 1,
  },
  {
    label: "自提",
    value: 2,
  },
  {
    label: "到店消费",
    value: 3,
  },
  {
    label: "快递、自提",
    value: 4,
  },
  {
    label: "全部支持",
    value: 5,
  },
]);

const pagination = ref({
  total: 10,
});
const formRef = ref<FormInst | null>(null);

const showModal = ref(false);
const popTitle: any = ref("添加店铺");
const params = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: "",
  user_id: "",
});

const formValue = ref({});

const rules = {
  businessId: {
    type: "array",
    required: false,
    trigger: ["blur", "change"],
    message: "请选择店铺",
  },
  categoryId: {
    type: "array",
    required: false,
    trigger: ["blur", "change"],
    message: "请选择商品分类",
  },
  goodsName: {
    required: true,
    trigger: ["blur"],
    message: "请输入",
  },
  subtitle: {
    required: true,
    trigger: ["blur"],
    message: "请输入",
  },
  goodsPrice: {
    required: true,
    trigger: ["blur"],
    message: "请输入",
  },
  scribePrice: {
    required: false,
    trigger: ["blur"],
    message: "请输入商品划线价格",
  },
  memberPrice: {
    required: false,
    trigger: ["blur"],
    message: "请输入商品会员价格",
  },
  goodsType: {
    type: "array",
    required: false,
    trigger: ["blur", "change"],
    message: "请选择商品配送方式",
  },
  stockNum: {
    required: true,
    trigger: ["blur"],
    message: "请输入",
  },
  rewardIntegral: {
    required: false,
    trigger: ["blur"],
    message: "请输入商品赠送积分",
  },
  previewUrl: {
    required: true,
    trigger: ["blur", "image"],
    message: "请上传商品预览封面",
  },
  rotationImgsJson: {
    required: false,
    trigger: ["blur"],
    message: "请上传商品轮播图",
  },
  contents: {
    required: false,
    trigger: ["blur"],
    message: "请填写富文本",
  },
};

const columns = [
  {
    title: "店铺ID",
    key: "businessId",
    ellipsis: {
      tooltip: true,
    },
    render: (item) => setStore(item),
  },
  {
    title: "店铺名称",
    key: "businessId",
    // width: 200,
    ellipsis: {
      tooltip: true,
    },
    render: (item) => setStoreName(item),
  },
  // {
  //   title: '商品分类',
  //   key: 'categoryId',
  //   // width: 200,
  //   ellipsis: {
  //     tooltip: true
  //   },
  //   render: (item) => setCategory(item)
  // },
  {
    title: "商品名称",
    key: "goodsName",
    // width: 200,
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: "规格类型",
    key: "goodsSkuType",
    ellipsis: {
      tooltip: true,
    },
    render: (item) => setSku(item),
  },
  {
    title: "商品封面",
    key: "previewUrl",
    ellipsis: {
      tooltip: true,
    },
    render: (item) => setImage(item),
  },

  {
    title: "商品价格",
    key: "goodsPrice",
    // width: 200,
    ellipsis: {
      tooltip: true,
    },
    render: (item) => setPrice(item),
  },
  {
    title: "划线价格",
    key: "scribePrice",
    // width: 200,
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: "商品已售",
    key: "goods_sales",
    // width: 200,
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: "商品库存",
    key: "stockNum",
    // width: 200,
    ellipsis: {
      tooltip: true,
    },
    render: (item) => setSkuStockNum(item),
  },
  //  {
  //   title: '限购',
  //   key: 'limitNum',
  //   // width: 200,
  //   ellipsis: {
  //     tooltip: true
  //   },

  // },

  {
    title: "状态",
    key: "status",
    ellipsis: {
      tooltip: true,
    },
    render: (item) => setStatus(item),
  },
  {
    title: "创建时间",
    key: "ctime",
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: "操作",
    key: "actions",
    width: 180,
    align: "right",
    fixed: "right",
    hideInExcel: true,

    render(row) {
      return [
        h(
          NButton,
          {
            size: "small",
            type: "primary",
            secondary: true,
            onClick: () => handleOpenRolesSet(row),
          },
          {
            default: () => "编辑",
            icon: () => h("i", { class: "i-fe:database" }),
          },
        ),

        h(
          NButton,
          {
            size: "small",
            type: "error",
            style: "margin-left: 12px;",
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => "删除",
            icon: () =>
              h("i", { class: "i-material-symbols:delete-outline text-14" }),
          },
        ),
      ];
    },
  },
];

function setStore(item) {
  try {
    return item.business.value;
  } catch (e) {
    if (item.otherConfigJson) {
      return "代码报错";
    }
  }
}

function setStoreName(item) {
  // console.log(JSON.parse(item.businessId),type)
  try {
    if (item.business.label) return item.business.label;
    else return "全部店铺";
  } catch (e) {
    if (item.otherConfigJson) {
      return "代码报错";
    }
  }
}
function setCategory(item) {
  // console.log(JSON.parse(item.businessId),type)
  try {
    if (item.category.label) return item.category.label;
    else return "无";
  } catch (e) {
    if (item.otherConfigJson) {
      return "代码报错";
    }
  }
}

function setSkuStockNum(item) {
  try {
    if (item.goodsSkuType == "单规格") {
      return item.stockNum;
    } else {
      var data = JSON.parse(item.goodsSkuJson);
      console.log(data.list1[0].skuStockNum);
      return data.list1[0].skuStockNum;
    }
  } catch (e) {
    return "规格价格有误";
  }
}

function setPrice(item) {
  try {
    if (item.goodsSkuType == "单规格") {
      return h(
        "span",
        { style: { color: "red" } },
        "￥" + item.goodsPrice,
      ); 
    } else {
      var data = JSON.parse(item.goodsSkuJson);
      // return data.list1[0].skuPrice
      return h(
        "span",
        { style: { color: "red" } },
        "￥" + data.list1[0].skuPrice,
      );
    }
  } catch (e) {
    return "规格价格有误";
  }
}

function setImage(item) {
  try {
    return h(NImage, {
        width: 60,
        src:
          Https() + item.previewUrl ||
          "https://q6.itc.cn/q_70/images03/20240319/5567d75589bd46439af8e835beeac44f.png",
      });
    // if (item.goodsSkuType == "单规格") {
    //   return h(NImage, {
    //     width: 60,
    //     src:
    //       Https() + item.previewUrl ||
    //       "https://q6.itc.cn/q_70/images03/20240319/5567d75589bd46439af8e835beeac44f.png",
    //   });
    // } else {
    //   var data = JSON.parse(item.goodsSkuJson);
    //   return h(NImage, {
    //     width: 60,
    //     src: data.list1[0].skuImage,
    //   });
    // }
  } catch (e) {
    if (item.otherConfigJson) {
      console.log(item.otherConfigJson);
    }
  }
}

function setPaypalType(item) {
  // console.log(JSON.parse(item.businessId),type)
  try {
    if (item.paypal_type) {
      if (item.paypal_type == 1) return "微信支付";
      if (item.paypal_type == 2) return "支付宝支付";
      if (item.paypal_type == 3) return "余额支付";
      if (item.paypal_type == 4) return "月卡支付";
      if (item.paypal_type == 5) return "微信,余额,支付宝";
      if (item.paypal_type == 6) return "全部";
    } else {
      return "全部店铺";
    }
  } catch (e) {
    if (item.otherConfigJson) {
      return "代码报错";
      console.log(item.otherConfigJson);
    }
  }
}
function setSku(item) {
  // if(item.goodsSkuType == '单规格')
  return item.goodsSkuType;
}
function setOrderType(item) {
  // console.log(JSON.parse(item.businessId),type)
  try {
    if (item.order_type) {
      if (item.order_type == 1) return "普通订单";
      if (item.order_type == 2) return "月卡订单";
      if (item.order_type == 3) return "补录订单";
      if (item.order_type == 4) return "积分订单";
      if (item.order_type == 5) return "余额订单";
    } else {
      return "全部店铺";
    }
  } catch (e) {
    if (item.otherConfigJson) {
      return "代码报错";
      console.log(item.otherConfigJson);
    }
  }
}

function goodsType(item) {
  // console.log(JSON.parse(item.businessId),type)
  try {
    if (item.goodsType) {
      if (item.goodsType == 1) return "快递";
      if (item.goodsType == 2) return "自提";
      if (item.goodsType == 3) return "到店消费";
      if (item.goodsType == 4) return "快递丶自提";
      if (item.goodsType == 5) return "全部支持";
    } else {
      return "全部店铺";
    }
  } catch (e) {
    if (item.otherConfigJson) {
      return "代码报错";
      console.log(item.otherConfigJson);
    }
  }
}

function setStatus(item) {
  // console.log(item)
  if (item.goods_status == "立即上架")
    return h("span", { style: { color: "green" } }, "上架");
  else return h("span", { style: { color: "red" } }, item.goods_status);
}
const data: any = ref([]);

async function handleDelete(id) {
  const res: any = await api.DeleteApi({
    id: id,
  });
  if (res.code == 200) {
    List();
    $message.success("删除成功!");
  } else {
  }
}
const messageParams: any = ref({
  show: false,
  status: "403",
  loading: true,
});

const uploadImage = () => {
  typeImage.value = "富文本";
  uploadShow.value = true;
};

const handleOpenRolesSet = (item) => {
  router.push({
    path: "/goods/edit",
    query: {
      goods_id: item.goods_id,
    },
  });
  // formValue.value = item;
  // if(formValue.value.businessId)
  //   formValue.value.businessId = item.businessId
  // else
  //   formValue.value.businessId = ''
  // if(formValue.value.categoryId == '0' || formValue.value.categoryId == 0 ||  formValue.value.categoryId == ['0'] ||  formValue.value.categoryId == []){
  //   formValue.value.categoryId = ""
  //   value.value = null
  // }

  // else{
  //   formValue.value.categoryId = Number(formValue.value.categoryId)
  //   value.value = Number(formValue.value.categoryId)
  // }

  // if(formValue.value.rotationImgsJson.length > 10)
  //   formValue.value.rotationImgsJson = item.rotationImgsJson.split(',')
  // else{
  //   if(formValue.value.rotationImgsJson.length > 0){

  //   }else{
  //     formValue.value.rotationImgsJson = []
  //   }
  // }

  // if(formValue.value.rewardIntegral || formValue.value.rewardIntegral == 0){
  //   formValue.value.rewardIntegral = String(formValue.value.rewardIntegral)
  // }

  // formValue.value.goodsType = Number(formValue.value.goodsType)

  //  // 回显规格

  // try{
  //   if(formValue.value.goodsSkuJson){

  //     goodsTherJson.value = JSON.parse(formValue.value.goodsSkuJson).list
  //     goodsSkuJson.value = JSON.parse(formValue.value.goodsSkuJson).list1

  //   }

  // }catch(e){

  // }

  // console.log(formValue.value)
  // // if(item.otherConfigJson)
  // //     formValue.value.otherConfigJson = JSON.parse(item.otherConfigJson)
  // popTitle.value = '编辑';
  // showModal.value = true;
};

function handlePreview1(file: UploadFileInfo) {
  const { url } = file;
  formValue.value.previewUrl = url as string;
}
function handlePreview2(file: UploadFileInfo) {
  const { url } = file;
  formValue.value.rotationImgsJson = url as string;
}

const EditorFun = (item) => {
  EditorShow.value = true;
};
const SkuShow = ref(false);
const SkuFun = (item) => {
  SkuShow.value = true;
};
async function List() {
  try {
    messageParams.value.loading = true;
    messageStatus.value = true;
    const res: any = await api.ListApi(params.value);
    if (res.code == 200) {
      setTimeout(() => {
        data.value = res.data.list;
        for (let index1 = 0; index1 < data.value.length; index1++) {
          for (let index = 0; index < storeOptions.value.length; index++) {
            if (
              storeOptions.value[index].value == data.value[index1].businessId
            ) {
              data.value[index1]["business"] = storeOptions.value[index];
              continue;
            }
          }
        }

        // for (let index1 = 0; index1 < data.value.length; index1++) {
        //   for (let index = 0; index < categoryOptions.value.length; index++) {

        //     if(categoryOptions.value[index].value == data.value[index1].categoryId){
        //       data.value[index1]['category'] = categoryOptions.value[index];
        //       continue;
        //     }
        //   }
        // }

        messageParams.value.loading = false;
        pagination.value.total = res.data.total;
      }, 500);
    } else {
      messageParams.value.show = false;
      messageParams.value.status = "500";
    }
  } catch (error) {
    console.error(error);
  }
}
const storeOptions = ref([]);
async function storeList() {
  const res: any = await api.storeListApi({
    pageNum: 1,
    pageSize: 300,
  });
  if (res.code == 200) {
    storeOptions.value = res.data.list.map((item) => {
      return {
        label: item.businessName,
        value: item.businessId,
      };
    });
  }
}
const categoryOptions = ref([]);
async function categoryList() {
  const res: any = await api.categoryListApi({
    pageNum: 1,
    pageSize: 500,
  });
  if (res.code == 200) {
    categoryOptions.value = res.data.list.map((item) => {
      return {
        label: item.categoryName,
        value: item.id,
      };
    });
  }
}

const queding = ref(0);
const confirmModal = () => {
  // 处理规格

  formValue.value.goodsSkuJson = {
    list: goodsTherJson.value,
    list1: goodsSkuJson.value,
  };
  SkuShow.value = false;
  queding.value = 1;
};

const addGoodsTherSku = () => {
  try {
    if (goodsTherJson.value.length >= 3) {
      return;
    }
    goodsTherJson.value.push({
      name: "其它规格",
      list: [
        {
          skuId: "",
          skuName: "",
          skuSort: 0,
        },
      ],
    });
  } catch (e) {
    goodsTherJson.value = [];
    goodsTherJson.value.push({
      name: "其它规格",
      list: [
        {
          skuId: "",
          skuName: "",
          skuSort: 0,
        },
      ],
    });
  }
};

const addGoodsTherSkuItem = (item, index, item1, index1) => {
  goodsTherJson.value[index].list.push({
    skuId: "",
    skuName: "",
    skuSort: 0,
  });
};

const addGoodsSku = () => {
  // 判断前面数据是否有其它规格
  // if(goodsSkuJson.value[goodsSkuJson.value.length-1].skuImage || goodsSkuJson.value[goodsSkuJson.value.length-1].skuStockNum || goodsSkuJson.value[goodsSkuJson.value.length-1].skuPrice){
  //   goodsSkuJson.value[goodsSkuJson.value.length-1].skuImage = ''
  //   goodsSkuJson.value[goodsSkuJson.value.length-1].skuStockNum = ''
  //   goodsSkuJson.value[goodsSkuJson.value.length-1].skuPrice = ''
  // }

  goodsSkuJson.value.push({
    skuId: "",
    skuName: "",
    skuPrice: "",
    skuStockNum: "",
    skuSort:
      Number(goodsSkuJson.value[goodsSkuJson.value.length - 1].skuSort) + 1,
    skuImage: "",
  });
};

function onClickAdd() {
  router.push({
    path: "/goods/add",
  });
  // value.value = null
  // formValue.value = {
  //   businessId:[],
  //   categoryId:"",
  //   extJson:true,
  //   status:true,
  //   goodsName:"",
  //   goodsSkuJson:"",
  //   goodsPrice:"",
  //   goodsStatus:true,
  //   goodsType:[],
  //   memberPrice:"",
  //   limitNum:"",
  //   packingFee:"",
  //   previewUrl:"",
  //   distributionFee:"",
  //   goodsBeginTime:"",
  //   goodsEndingTime:"",
  //   goodsDetails:"",
  //   goodsDetailsJson:"",
  //   rewardIntegral:"",
  //   rotationImgsJson:[],
  //   scribePrice:"",
  //   stockNum:null,
  //   contents:"",
  //   subtitle:"",
  //   keywords:"",
  //   effectDays:"",
  //   goodsViewCount:"",
  //   paypal_type:null,
  //   order_typ:null
  // }
  // popTitle.value = '添加商品'
  // showModal.value = true
}
async function submitCallback() {
  messageParams.value.loading = true;
  formRef.value?.validate((errors) => {
    if (!errors) {
      formValue.value.user_id = route.query.user_id;
      if (popTitle.value == "添加商品") AddFun();
      else EditFun();
    } else {
      showModal.value = true;
      return;
    }
  });
}

async function AddFun() {
  formValue.value.user_id = "";
  const newData = formValue.value;
  queding.value = 0;
  formValue.value.goodsSkuJson = JSON.stringify(formValue.value.goodsSkuJson);
  newData.rotationImgsJson = String(newData.rotationImgsJson);
  messageParams.value.loading = true;
  // newData.otherConfigJson = JSON.stringify(formValue.value.otherConfigJson)
  const res: any = await api.AddApi(newData);
  if (res.code == 200) {
    List();
    formValue.value = {
      businessId: [],
      categoryId: "",
      extJson: true,
      status: true,
      goodsName: "",
      goodsSkuJson: "",
      goodsPrice: "",
      goodsStatus: true,
      goodsType: [],
      memberPrice: "",
      limitNum: "",
      packingFee: "",
      previewUrl: [],
      distributionFee: "",
      goodsBeginTime: "",
      goodsEndingTime: "",
      goodsDetails: "",
      goodsDetailsJson: "",
      rewardIntegral: "",
      rotationImgsJson: [],
      scribePrice: "",
      stockNum: null,
      contents: "",
      subtitle: "",
      keywords: "",
      effectDays: "",
      goodsViewCount: "",
      paypal_type: null,
      order_typ: null,
    };
    showModal.value = false;
    $message.success("添加成功!");
  } else {
    $message.error(res.message);
  }
}

async function EditFun() {
  // 处理规格样式
  if (queding.value == 1)
    formValue.value.goodsSkuJson = JSON.stringify(formValue.value.goodsSkuJson);

  formValue.value.user_id = "";
  const newData = formValue.value;
  newData.rotationImgsJson = String(newData.rotationImgsJson);
  messageParams.value.loading = true;

  const res: any = await api.EditApi(formValue.value);
  if (res.code == 200) {
    List();
    showModal.value = false;
    $message.success("编辑成功!");
    queding.value = 0;
  } else {
    $message.error(res.message);
  }
}

function pageNext(page) {
  params.value.pageNum = page;
  List();
}
function sizeNext(size) {
  params.value.pageNum = 1;
  params.value.pageSize = size;
  List();
}

function cancelCallback() {
  List();
  showModal.value = false;
}
const typeImage = ref("");
const skuIndex = ref("");
function changeImage(type, index) {
  if (type == "规格图") {
    skuIndex.value = index;
  }
  typeImage.value = type;
  uploadShow.value = true;
}

function goTo(path) {
  router.push(path);
}
</script>

<style scoped lnag="scss">
.box {
  height: 75vh;
  overflow-y: auto;
}
.table-box {
  padding: 20px;
}
.box-modal {
  /* width: 850px; */
  /* height: 620px; */
  position: relative;
  /* width: 400px; */
  /* height: 350px; */
}
.pagination {
  display: flex;
  justify-content: right;
  /* height: 60px; */
  gap: 10px;
  align-items: center;
  position: relative;
  top: 20px;
  right: 30px;
}
.header {
  display: flex;
  gap: 10px;
}
.Message {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 200px;
}

.formClass {
  gap: 20px;
  display: grid;
  overflow-y: auto;
  grid-template-columns: repeat(2, 1fr);
  /* height: 600px; */
}
.EditorClass {
  display: flex;
  justify-content: center;
  align-items: center;
}
.pcEditorClass {
  width: 400px;
  height: 600px;
  /* height: 650px; */
}
.Editorfloot {
  border-top: 1px solid #ccc;
  display: flex;
  align-items: center;
  width: 100%;
  gap: 20px;
  justify-content: center;
  padding-top: 25px;
  margin-top: 25px;
}

.xcxEditorClass {
  height: 550px;
  width: 320px;
  overflow-y: auto;
}
.xcxEditorClass::-webkit-scrollbar {
  display: block;
}
.xcxEditorClass.hide-scrollbar::-webkit-scrollbar {
  display: none;
}
.Editorbox {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}
.goodsFloot {
  z-index: 999;
  position: absolute;
  width: 100%;

  background: #fff;
}
.imageUpload {
  width: 100px;
  height: 100px;
  border: 1px solid #eee;
  display: flex;
  justify-content: center;
  border-radius: 6px;
  align-items: center;
}
.imageUpload:hover {
  border: 1px solid rgb(49, 108, 114);
}
.skuInput {
  position: relative;
  border: 1px solid #eee;

  padding: 20px 12px;
  gap: 12px;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  transition-property: background;
  transition-duration: 0.25s, 0.5s;
}
.skuInput:hover {
  background: #eee;
  .skuDelete {
    display: flex;
  }
}
.skuDelete {
  position: absolute;
  top: -20px;
  right: 0px;
  display: none;
}
.skubitian {
  padding: 10px 0;
  .skuTitle {
    font-size: 16px;
    font-weight: bold;
    padding: 10px 0;
  }
}
</style>
